//
//  HomeViewController.m
//  B2C
//
//  Created by 李小龙 on 2017/7/18.
//  Copyright © 2017年 lixiaolong. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeMainCell.h"

#import "SearchCacheViewController.h"
#import "CommodityModel.h"
#import "GoodDetailViewController.h"
#import "GroupScanViewController.h"
#import "SearchResultViewController.h"
#import "AdvWebViewController.h"
// firstCell
#import "HomeFirstTableViewCell.h"

// model
#import "HomeRecommendModel.h"
// title
#import "TitleSelectView.h"
#import "ClassifyFirstModel.h"
// others
#import "HomeOthersModel.h"
//
#import "HomeAllClassGoodsModel.h"
#import "MineMessageViewController.h"
#import "RedPointButton.h"

@interface HomeViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UISearchBarDelegate, UIScrollViewDelegate>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *titleArr;  // title
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UIView *searchView;

@property (nonatomic, strong) TitleSelectView *titleView;

@property (nonatomic, strong) RedPointButton *messageButton;
@property (nonatomic, strong) UIButton *scanButton;

@property (nonatomic, assign) NSInteger currentIndex;

@property (nonatomic, strong) HomeRecommendModel *recommendModel;
@property (nonatomic, strong) NSMutableArray *recommendArr; // 推荐数组
@property (nonatomic, strong) NSMutableArray *listArr;      // 其它列表数组
@property (nonatomic, strong) NSMutableDictionary *otherDic;// 其它分类的数组
@property (nonatomic, strong) NSMutableArray *allClassGoodsArr; // 首页所有分类的商品
@end

@implementation HomeViewController
#pragma mark - viewController
- (instancetype)init {
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = NO;
        self.navigationItem.leftBarButtonItem = nil;
        
        _titleArr = [NSMutableArray array];
        
        _recommendArr = [NSMutableArray array];
        _listArr = [NSMutableArray array];
        _currentIndex = 0;
        _otherDic = [NSMutableDictionary dictionary];
        _recommendModel = [[HomeRecommendModel alloc] init];
        _allClassGoodsArr = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self configureUI];
    [self loadAllData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
    [[self.navigationController.navigationBar subviews].firstObject.subviews.firstObject setAlpha:0.0];
    
    if ([ShowRedPoint shareInstance].isShowMessage) {
        [self.messageButton.redPoint setHidden:NO];
    } else {
        [self.messageButton.redPoint setHidden:YES];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [[self.navigationController.navigationBar subviews].firstObject.subviews.firstObject setAlpha:1.0];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.titleView.frame = CGRectMake(0, 0, ScreenWidth, self.titleView.height);
    self.collectionView.frame = CGRectMake(0, self.titleView.height, self.view.width, self.view.height - self.titleView.height);
}

#pragma mark - Method
- (void)configureUI {
    self.title = @"首页";
    [self.view addSubview:self.titleView];
    [self.view addSubview:self.collectionView];
    
    __weak typeof(self) weakSelf = self;
    self.titleView.block = ^(NSInteger index) {
        
        
        [weakSelf scrollIndexOrSelectIndex:index];
        [weakSelf.collectionView scrollRectToVisible:CGRectMake(index * weakSelf.collectionView.width, weakSelf.titleView.height, weakSelf.collectionView.width, weakSelf.collectionView.height) animated:YES];
        
    };
    [self configureNavigation];
}

- (void)configureTitleView {
    NSMutableArray *arr = [self getFirstStr:self.titleArr];
    [arr insertObject:@"推荐" atIndex:0];
    
    [self.titleView setupWithTitleStrsArr:arr withIndex:self.currentIndex];
    [self.collectionView reloadData];
}

- (void)configureNavigation {
    
    
//    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo"]]];
//    self.navigationItem.leftBarButtonItem = leftItem;
    UIButton *logoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [logoButton setFrame:CGRectMake(0, 0, 59, 29)];
    [logoButton setImage:[UIImage imageNamed:@"logo"] forState:UIControlStateNormal];
    [logoButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    
    [logoButton setUserInteractionEnabled:NO];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:logoButton];
    
    
    
    UIView *view = [UIView new];
    view.frame = CGRectMake(0, 0, 65, 20);
    self.messageButton.frame = CGRectMake(view.width-self.messageButton.width, 0, self.messageButton.width, self.messageButton.height);
    self.scanButton.frame = CGRectMake(self.messageButton.mj_x-15-self.scanButton.size.width, 0, self.scanButton.size.width, self.scanButton.size.height);
    
    [view addSubview:self.scanButton];
    [view addSubview:self.messageButton];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:view];
    
    
    //    UIBarButtonItem *scanItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"scanning"] style:UIBarButtonItemStylePlain target:self action:@selector(scanButtonClick)];
    //    UIBarButtonItem *messageItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"information"] style:UIBarButtonItemStylePlain target:self action:@selector(messageButtonClick)];
    //    self.navigationItem.rightBarButtonItems = @[messageItem, scanItem];
    
    self.navigationItem.titleView = self.searchView;
}

- (NSMutableArray <NSString *> *)getFirstStr:(NSArray <ClassifyFirstModel *> *)arr {
    NSMutableArray *firstArr = [NSMutableArray array];
    for (ClassifyFirstModel *model in self.titleArr) {
        [firstArr addObject:model.gcname];
    }
    return firstArr;
}

- (void)reloadUI {
    
}

- (void)scrollIndexOrSelectIndex:(NSInteger)index {
    self.currentIndex = index;
    [self loadOhtersListData:index withCell:nil];
}

#pragma mark - Action
- (void)leftButtonClick {
    
}

- (void)scanButtonClick {
    GroupScanViewController *scanViewController = [[GroupScanViewController alloc] init];
    [self.navigationController pushViewController:scanViewController animated:YES];
}

- (void)messageButtonClick {
    MineMessageViewController *messageVC = [[MineMessageViewController alloc] init];
    [self.navigationController pushViewController:messageVC animated:YES];
}

#pragma mark - NetWork
- (void)loadAllData {
    [self getFirstClass];
    [self loadRecommendList:nil];
    [self loadAllGoodsList:nil];
}

- (void)getFirstClass {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Get_Goodsclass parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            NSArray *data = [responseDic safeJsonObjectForKey:@"data"];
            [weakSelf.titleArr removeAllObjects];
            for (NSDictionary *modelDic in data) {
                ClassifyFirstModel *model = [ClassifyFirstModel mj_objectWithKeyValues:modelDic];
                [weakSelf.titleArr addObject:model];
            }
            [weakSelf configureTitleView];
        } else {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:nil animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD showError:weakSelf.view title:@"" code:nil animated:YES];
        
    } isNeedCache:YES];
}

- (void)loadRecommendList:(HomeFirstTableViewCell *)cell {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Get_Home_List parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            NSDictionary *modelDic = [responseDic safeJsonObjectForKey:@"data"];
            weakSelf.recommendModel = [HomeRecommendModel mj_objectWithKeyValues:modelDic];
            if (cell) {
                [cell setShowData:weakSelf.recommendModel];
            }
        } else {
            [MBProgressHUD showError:weakSelf.view title:@"" code:code animated:YES];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        
    } isNeedCache:YES];
}

- (void)loadOhtersListData:(NSInteger)index withCell:(HomeMainCell *)cell {
    if (index == 0) {
        return;
    }
    index = index - 1;
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    ClassifyFirstModel *titleModel = [self.titleArr safeObjectAtIndex:index];
    [parameters safeSetObject:titleModel.gcid forKey:@"gcid"];
    [parameters safeSetObject:@"1" forKey:@"pageNumber"];
    [parameters safeSetObject:@"4" forKey:@"pageSize"];
    
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_ALL_GoodsTwoClass parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            NSArray *dataArr = [responseDic safeJsonObjectForKey:@"data"];
            NSMutableArray *arr = [NSMutableArray array];
            for (NSDictionary *modelDic in dataArr) {
                HomeOthersModel *otherModel = [HomeOthersModel mj_objectWithKeyValues:modelDic];
                [arr addObject:otherModel];
            }
            [weakSelf.otherDic setObject:arr forKey:@(index)];
            if (cell) {
                ClassifyFirstModel *titleModel = [weakSelf.titleArr safeObjectAtIndex:index];
                [cell setShowArr:arr headImage:titleModel.gcimg];
            } else {
                [weakSelf.collectionView reloadData];
            }
        } else {
            [MBProgressHUD showError:weakSelf.view title:@"" code:code animated:YES];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        
    } isNeedCache:NO];
}

- (void)loadAllGoodsList:(HomeFirstTableViewCell *)cell  {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Get_Goods_All_Class parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            NSArray *dataArr = [responseDic safeJsonObjectForKey:@"data"];
            [weakSelf.allClassGoodsArr removeAllObjects];
            for (NSDictionary *modelDic in dataArr) {
                HomeAllClassGoodsModel *goodsModel = [HomeAllClassGoodsModel mj_objectWithKeyValues:modelDic];
                [weakSelf.allClassGoodsArr addObject:goodsModel];
            }
            if (cell) {
                [cell setOthersGoodsData:weakSelf.allClassGoodsArr];
            } else {
                [weakSelf.collectionView reloadData];
            }
        } else {
            [MBProgressHUD showError:weakSelf.view title:@"" code:code animated:YES];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        
    } isNeedCache:YES];
}

#pragma mark -- UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }
    return self.titleArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) weakSelf = self;
    if (indexPath.section == 0) {
        HomeFirstTableViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"fristTableViewCell" forIndexPath:indexPath];
        [cell setShowData:self.recommendModel];
        [cell setOthersGoodsData:self.allClassGoodsArr];
        cell.backgroundColor = [UIColor orangeColor];
        
        cell.block = ^(NSInteger index, CommodityModel *model) {
            if (index == -1) {
                if (TextIsNotNil(model.gid)) {
                    GoodDetailViewController *goodVC = [[GoodDetailViewController alloc] init];
                    goodVC.gid = model.gid;
                    [weakSelf.navigationController pushViewController:goodVC animated:YES];
                }
            } else {
                SearchResultViewController *searchReusltVC = [[SearchResultViewController alloc] init];
                if (index == 0) {
                    searchReusltVC.currentType = GoodsVCTypeForRecommend;
                } else if (index == 1) {
                    searchReusltVC.currentType = GoodsVCTypeForNew;
                }
                [weakSelf.navigationController pushViewController:searchReusltVC animated:YES];
            }
        };
        __strong HomeFirstTableViewCell *strongCel = cell;

        cell.headerRefresh = ^{
            [weakSelf loadRecommendList:strongCel];
            [weakSelf loadAllGoodsList:strongCel];
        };
        
        cell.bannerBlock = ^(NSInteger index) {
            // header上面的轮播图回调
            NSLog(@"banner 轮播图 index = %ld", (long)index);
            HomeAdvModel *model = [weakSelf.recommendModel.adv safeObjectAtIndex:index];
            if (TextIsNotNil(model.alink)) {
                AdvWebViewController *advWebView = [[AdvWebViewController alloc] init];
                advWebView.url = model.alink;
                [weakSelf.navigationController pushViewController:advWebView animated:YES];
            }
        };
        cell.advBlock = ^(NSInteger index) {
            // 第二个section以后，每个section的广告图
            NSLog(@"section 广告图 index = %ld", (long)index);
            HomeAllClassGoodsModel *classGoodsModel = [weakSelf.allClassGoodsArr safeObjectAtIndex:index];
            if (classGoodsModel.isgoods) {
                if (TextIsNotNil(classGoodsModel.gcurl)) {
                    GoodDetailViewController *goodVC = [[GoodDetailViewController alloc] init];
                    goodVC.gid = classGoodsModel.gcurl;
                    [weakSelf.navigationController pushViewController:goodVC animated:YES];
                }
            } else {
                if (TextIsNotNil(classGoodsModel.gcurl)) {
                    AdvWebViewController *advWebView = [[AdvWebViewController alloc] init];
                    advWebView.url = classGoodsModel.gcurl;
                    [weakSelf.navigationController pushViewController:advWebView animated:YES];
                }
            }
        };
        return cell;
    }
    
    NSArray *arr = [self.otherDic objectForKey:@(indexPath.row)];
    HomeMainCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"tableViewCell" forIndexPath:indexPath];
    ClassifyFirstModel *titleModel = [self.titleArr safeObjectAtIndex:indexPath.row];
    [cell setShowArr:arr headImage:titleModel.gcimg];

    cell.block = ^(NSString *commodityId) {
        NSLog(@"%@", commodityId);
        if (TextIsNotNil(commodityId)) {
            GoodDetailViewController *goodVC = [[GoodDetailViewController alloc] init];
            goodVC.gid = commodityId;
            [weakSelf.navigationController pushViewController:goodVC animated:YES];
        }
    };
    
    __strong HomeMainCell *strongCell = cell;
    cell.headerRefresh = ^{
        [weakSelf loadOhtersListData:weakSelf.currentIndex withCell:strongCell];
    };
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(self.view.width, self.view.height - self.titleView.height);
}

#pragma mark - UISearchBarDelegate

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    SearchCacheViewController *searchCacheVC = [[SearchCacheViewController alloc] init];
    [self.navigationController pushViewController:searchCacheVC animated:YES];
    
    return NO;
}

#pragma mark - UIScrollViewDeleagte
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView != self.collectionView) {
        return;
    }
    CGFloat x = scrollView.contentOffset.x;
    CGFloat page = x / self.view.width;
    NSInteger index = (page + 0.3) / 1;
    [self.titleView setToShowIndex:index withAnimation:YES];
    [self scrollIndexOrSelectIndex:index];
    NSLog(@"scrollViewDidEndDecelerating: %f, index:%ld", page, (long)index);
}

#pragma mark -- Getters
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        flowLayout.itemSize = CGSizeMake(self.view.width, self.view.height - self.titleView.height);
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal; // 横向
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _collectionView.pagingEnabled = YES;
        _collectionView.alwaysBounceHorizontal = YES;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        
        [_collectionView registerNib:[UINib nibWithNibName:@"HomeFirstTableViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"fristTableViewCell"];
        [_collectionView registerNib:[UINib nibWithNibName:@"HomeMainCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"tableViewCell"];
    }
    return _collectionView;
}

- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth-75-81, 28)];
        _searchBar.delegate = self;
        [_searchBar setTintColor:[UIColor blueColor]];
        _searchBar.backgroundImage = [UIImage imageWithColor:[UIColor whiteColor]];
        [_searchBar changeLeftPlaceholder:@"搜索你想要的"];
        
        UITextField *searchField = [_searchBar valueForKey:@"searchField"];
        searchField.mj_h = 28;
        searchField.font = TextNormalFontSize(14);
    }
    return _searchBar;
}
- (UIView *)searchView {
    if (!_searchView) {
        _searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth-75-81, 28)];
        [_searchView setBackgroundColor:[UIColor whiteColor]];
        [_searchView setCircleWithColor:[UIColor borderColor] borderWidth:1.0 cornerRadius:0];
        [_searchView addSubview:self.searchBar];
    }
    return _searchView;
}

- (TitleSelectView *)titleView {
    if (!_titleView) {
        _titleView = [[TitleSelectView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 32)];
    }
    return _titleView;
}

- (NSMutableArray *)getTestData {
    NSMutableArray *arr = [NSMutableArray array];
    CommodityModel *model = [[CommodityModel alloc] init];
    
    for (NSInteger i = 0; i < 20; i++) {
        [arr addObject:model];
    }
    
    return arr;
}

- (RedPointButton *)messageButton {
    if (!_messageButton) {
        _messageButton = [RedPointButton buttonWithType:UIButtonTypeCustom];
        [_messageButton setImage:[UIImage imageNamed:@"information"] forState:UIControlStateNormal];
        [_messageButton addTarget:self action:@selector(messageButtonClick) forControlEvents:UIControlEventTouchUpInside];
        _messageButton.size = CGSizeMake(22, 20);
    }
    return _messageButton;
}

- (UIButton *)scanButton {
    if (!_scanButton) {
        _scanButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_scanButton setImage:[UIImage imageNamed:@"scanning"] forState:UIControlStateNormal];
        [_scanButton addTarget:self action:@selector(scanButtonClick) forControlEvents:UIControlEventTouchUpInside];
        _scanButton.size = CGSizeMake(22, 20);
    }
    return _scanButton;
}


@end
